#    This file is part of django_ip2country.
#    django_ip2country is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    django_ip2country is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with django_ip2country.  If not, see <http://www.gnu.org/licenses/>.
#    Author: Esteban Feldman esteban.feldman@gmail.com


from django_ip2country.models import Ip2Country

def ip2long(ip):
    ip_array = ip.split('.')
    ip_long = int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + int(ip_array[2]) * 256 + int(ip_array[3])
    return ip_long

def get_country(value):
    value = ip2long(value)
    try:
        # ip of comment has to be in a range of an ip-to-country object IP_FROM and IP_TO
        iptc = Ip2Country.objects.get(ip_from__lte=value, ip_to__gte=value)
    except Ip2Country.DoesNotExist:
        return None
    return iptc

